<template>
  <view class="edit-data">
    <view class="header-box">
      <img :src="getImageUrl(profileInfo.attr?.faceUrl)" class="img" @click="() => popupHeader.open()">
      <view>选择或上传头像</view>
      <img class="photo" src="https://img.qumoyugo.com/webimgbg/pet-round-camera-yls.png">
    </view>
    <uni-list class="user-edit" :border="false">
      <uni-list-item title="昵称" showArrow clickable @click="editNickname('nickname')">
        <template #footer>
          <view class="lext-ftsj" style="text-align: right;">
            {{ profileInfo.attr?.nickname }}
          </view>
        </template>
      </uni-list-item>
      <uni-list-item title="性别" showArrow clickable @click="editSex">
        <template #footer>
          <img :src="`https://img.qumoyugo.com/webimgbg/picopino_icon_sex_new_${profileInfo.attr?.sex}.png`" style="width: 36rpx;height: 36rpx;" v-if="profileInfo.attr?.sex">
        </template>
      </uni-list-item>
      <uni-list-item title="简介" showArrow clickable @click="editNickname('briefIntro')">
        <template #footer>
          <view class="lext-ftsj" :style="{ textAlign: profileInfo.attr?.briefIntro.length > 20 ? '' : 'right' }">
            {{ profileInfo.attr?.briefIntro }}
          </view>
        </template>
      </uni-list-item>
      <uni-list-item title="背景图" showArrow clickable @click="() => popupBackground.open()">
        <template #footer>
          <img :src="getImageUrl(profileInfo.attr?.backgroundImage)" style="width: 100rpx;height: 80rpx;border-radius: 12rpx;" v-if="profileInfo.attr?.backgroundImage">
        </template>
      </uni-list-item>
    </uni-list>
    <view class="preference">
      <view class="title">我的偏好</view>
      <view class="items">
        <view class="tag" v-for="preference in preferenceList" :key="preference" :class="preferenceCurrent.indexOf(preference) === -1 ? '' : 'active'" @click="selectPreference(preference)">{{ preference }}</view>
      </view>
    </view>
    <view class="u-center" style="font-size: 13px; color: #999;margin-top: 20px;">
      个人资料完成度：{{ profileInfo.perfection }}
    </view>
    <canvas canvas-id="firstCanvas" id="canvasImg"></canvas>
    <uni-popup ref="popupInputName" type="bottom" :safe-area="false" background-color="#ffffff"  @maskClick="closeInputName">
      <view class="input-bg-user" style="flex-wrap:wrap">
        <template v-if="currentInputName === 'nickname'">
          <input v-model="inputValue" maxlength="15"
            placeholderStyle="color:#333333;font-size:13px;" trim :focus="autoFocus"
            class="input-b"
            placeholder="请输入昵称" />
        </template>
        <template v-if="currentInputName === 'briefIntro'">
          <textarea v-model="inputValue" maxlength="300" auto-height
            placeholderStyle="color:#333333;font-size:13px;" trim :focus="autoFocus"
            class="input-b" style="line-height: 20px;"
            placeholder="简单介绍一下你和你家主子吧~" />
            <view style="height: 378px;"></view>
        </template>
        <view class="btn-submit" @click="submitInput">确认</view>
      </view>
    </uni-popup>
    <uni-popup ref="popupSex" background-color="#fff" type="bottom">
      <view class="sex-box">
        <view style="border-bottom: 1rpx solid #eeeeee;" @click="submitSex(1)">男</view>
        <view @click="submitSex(2)">女</view>
      </view>
    </uni-popup>
    <uni-popup ref="popupBackground" background-color="#fff" type="bottom">
      <view class="sex-box">
        <view style="border-bottom: 1rpx solid #eeeeee;" @click="uploadImage('Background')">上传背景图</view>
        <view @click="openBackgroundList">选择背景</view>
      </view>
    </uni-popup>
    <uni-popup ref="popupBackgroundList" background-color="#fff" type="bottom">
      <view class="background-list">
        <view class="title" style="margin-bottom: 20rpx;text-align:right;">
          <uni-icons type="closeempty" size="18" color="#999999" style="font-weight:300" @click="() => popupBackgroundList.close()"></uni-icons>
        </view>
        <view class="list-items">
          <view class="item" v-for="(imagelist, index) in backImageList" :key="index">
            <view class="grd-al" v-for="image in imagelist" :key="image.img" @click="selectBackImage(image.img)">
              <img :src="`https://img.qumoyugo.com${image.img}`" :style="{ opacity: currentBg === image.img ? '1' : '0.7'}" style="width: 100%;height: 100%;">
              <view class="tips" v-if="currentBg === image.img">
                <img src="https://img.qumoyugo.com/img/RP4XYCK8SGI4RJ2NETU631667280898778.png" class="img">
              </view>
            </view>
          </view>
        </view>
        <view class="bottom-b" :style="{ background: currentBg ? '#000000' : '#999999'}" @click="editBackground">
          确定
        </view>
      </view>
    </uni-popup>
    <uni-popup ref="popupHeaderList" background-color="#fff" type="bottom">
      <view class="background-list">
        <view class="title" style="margin-bottom: 20rpx;text-align:right;">
          <uni-icons type="closeempty" size="18" color="#999999" style="font-weight:300"
            @click="() => popupHeaderList.close()"></uni-icons>
        </view>
        <view class="header-list-items">
          <view class="hes-hek" v-for="avatar in avatarList" :key="avatar">
            <img :src="getImageUrl(avatar)" class="header-img" :style="{ opacity: currentHeader === avatar ? '1' : '0.7'}" @click="selectHeader(avatar)">
            <view class="tips" v-if="currentHeader === avatar">
              <img src="https://img.qumoyugo.com/img/RP4XYCK8SGI4RJ2NETU631667280898778.png" class="img">
            </view>
          </view>
          <view class="hes-hek">&nbsp;</view>
        </view>
        <view class="bottom-b" :style="{ background: currentHeader ? '#000000' : '#999999'}" @click="editHeader">
          确定
        </view>
      </view>
    </uni-popup>
    <uni-popup ref="popupHeader" background-color="#fff" type="bottom">
      <view class="sex-box">
        <view style="border-bottom: 1rpx solid #eeeeee;" @click="chooseHeader">选择头像</view>
        <view style="border-bottom: 1rpx solid #eeeeee;"  @click="uploadImage('Header')">上传头像</view>
        <view @click="openImageDetail">查看大图</view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, getCurrentInstance, onMounted, watch } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useStore } from '@/store'
import { storage } from '@/utils/utils'
import { creatMapHeader } from '@/minxin/minxins'
import { SAVE_DEFAULT_AVATAR, SAVE_COMMON_IMAGE } from '@/assets/js/config'
// minxins混入
const { drawHeader } = creatMapHeader()
const store = useStore()
const { $https } = getCurrentInstance().appContext.config.globalProperties
const avatarList = ref([])
const preferenceList = ref([])
const backImageList = ref([])
const preferenceCurrent = ref([])
const popupInputName = ref(null)
const popupSex = ref(null)
const popupBackground = ref(null)
const popupBackgroundList = ref(null)
const popupHeader = ref(null)
const popupHeaderList = ref(null)
const autoFocus = ref(false)
const inputValue = ref('')
const currentBg = ref('')
const currentHeader = ref('')
const imgHeader = ref('')
const currentInputName = ref('') // 当前选择输入框名称
// #ifdef MP-WEIXIN
const boardHeight = ref(0) // 监听键盘的高度变化
// #endif
const profileInfo = computed(() => {
  return store.state.profile || {}
})

watch(() => profileInfo.value, (newValue) => {
  if (newValue) {
    const pre = newValue.attr?.preference || ''
    preferenceCurrent.value = pre ? pre.split(',') : []
  }
}, { immediate: true })
// watch(() => boardHeight.value, (newValue) => {
//   if (newValue === 0) {
//     popupInputName.value.close()
//     // inputValue.value = ''
//     autoFocus.value = false
//   }
// })
onMounted(() => {
  getPreference()
  // #ifdef MP-WEIXIN
  uni.onKeyboardHeightChange(res => {
    console.log('键盘高度', res.height)
    boardHeight.value = res.height
  })
  // #endif
})
onShow(() => {
  const avatar = storage.get(SAVE_DEFAULT_AVATAR)
  const image = storage.get(SAVE_COMMON_IMAGE)
  if (avatar) {
    uni.showLoading({
      title: '头像生成中...'
    })
    drawHeader(profileInfo.value.attr.sex, avatar, (mapHeader) => {
      if (mapHeader) {
        editProfile({ face: avatar, mapHeader })
        uni.hideLoading()
      }
    })
    storage.remove(SAVE_DEFAULT_AVATAR)
  }
  if (image) {
    editProfile({ backgroundImage: image })
    storage.remove(SAVE_COMMON_IMAGE)
  }
})
// 图片全路径处理
const getImageUrl = (imageUrl) => {
  imageUrl = imageUrl || ''
  if (imageUrl.indexOf('https') === -1) {
    return `https://img.qumoyugo.com${imageUrl}`
  } else {
    return imageUrl
  }
}
const getPreference = () => {
  $https({
    url: '/preference',
    type: ''
  }).then((res) => {
    if (res.code === 0) {
      avatarList.value = res.data.avatarList
      preferenceList.value = res.data.preferenceList
      backImageList.value = [
        [...res.data.backImageList.slice(0, 2)],
        [...res.data.backImageList.slice(2, 4)],
        [...res.data.backImageList.slice(-2)]
      ]
    }
  })
}
const selectPreference = (item) => {
  const index = preferenceCurrent.value.indexOf(item)
  if (index === -1) {
    preferenceCurrent.value.push(item)
  } else {
    preferenceCurrent.value.splice(index, 1)
  }
  editProfile({ preference: preferenceCurrent.value.join(',') })
}
const editNickname = (value) => {
  currentInputName.value = value
  inputValue.value = ''
  popupInputName.value.open()
  autoFocus.value = true
}
const submitInput = () => {
  if (currentInputName.value === 'nickname' && !inputValue.value) {
    uni.showToast({
      title: '昵称不能为空',
      icon: 'none'
    })
    return false
  }
  popupInputName.value.close()
  editProfile({ [currentInputName.value]: inputValue.value })
  // inputValue.value = ''
  autoFocus.value = false
}
// 关闭输入框
const closeInputName = () => {
  popupInputName.value.close()
  // inputValue.value = ''
  autoFocus.value = false
}
const editSex = () => {
  popupSex.value.open()
}
// 选择头像
const selectHeader = (avatar) => {
  currentHeader.value = avatar
  console.log(444, avatar)
}
// 打开背景图层
const openBackgroundList = () => {
  popupBackground.value.close()
  popupBackgroundList.value.open()
}
// 选择背景
const selectBackImage = (img) => {
  currentBg.value = currentBg.value === img ? '' : img
}
// 修改背景
const editBackground = () => {
  if (!currentBg.value) return false
  popupBackgroundList.value.close()
  editProfile({ backgroundImage: currentBg.value })
}
// 选择头像
const uploadImage = (name) => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album'],
    success: (res) => {
      if (name === 'Background') {
        popupBackground.value.close()
      }
      if (name === 'Header') {
        popupHeader.value.close()
      }
      console.log(99999, res.tempFilePaths)
      uni.navigateTo({
        url: `/user/cropper?path=${res.tempFilePaths[0]}&orgin=${name === 'Background' ? 'edid' : 'first'}`
      })
    }
  })
}
// 修改性别
const submitSex = (value) => {
  const faceUrl = profileInfo.value.attr?.faceUrl
  drawHeader(value, faceUrl, (mapHeader) => {
    popupSex.value.close()
    editProfile({ sex: value, mapHeader })
  })
}
// 提交数据
const editProfile = (data) => {
  $https({
    url: '/profile',
    method: 'put',
    type: '',
    data
  }).then(res => {
    if (res.code === 0) {
      $https({
        url: '/profile',
        type: ''
      }).then(res1 => {
        if (res1.code === 0) {
          store.commit('setProfile', res1.data)
          // 同步Im数据
          // importAccountToIM(res1.data.attr.phone, res1.data.attr.faceUrl, res1.data.attr.nickname)
        }
      })
    }
  })
}
// 头像修改
const editHeader = () => {
  uni.showLoading({
    title: '头像生成中...'
  })
  console.log(profileInfo.value.attr.sex)
  drawHeader(profileInfo.value.attr.sex, currentHeader.value, (img) => {
    imgHeader.value = img
    if (img) {
      uni.hideLoading()
      editProfile({ face: `https://img.qumoyugo.com${currentHeader.value}`, mapHeader: imgHeader.value })
      popupHeaderList.value.close()
    }
  })
}
// 点击查看图片
const openImageDetail = (item) => {
  const _url = getImageUrl(profileInfo.value.attr?.faceUrl)
  popupHeaderList.value.close()
  uni.previewImage({
    urls: [_url]
  })
}
// 选择头像
const chooseHeader = () => {
  popupHeader.value.close()
  popupHeaderList.value.open()
}
</script>

<style scoped lang="scss">
.edit-data{
  padding: 40rpx;
}
.preference{
  border-top: 0.5px solid #f2f2f2;
  .title{
    color: #666666;
    font-size: 14px;
    margin: 30rpx 0;
  }
  .tag{
    font-size: 24rpx;
    line-height: 24rpx;
    padding: 13rpx 16rpx;
    border-radius: 32rpx;
    border: 1rpx solid #979797;
    color: #333333;
    margin-right: 18rpx;
    margin-bottom: 18rpx;
    display: inline-block;
    &.active{
      background-color: #000000;
      color: #ffffff;
      border-color: #000000;
    }
  }
}
.input-bg-user{
  padding: 24rpx 30rpx;
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  .btn-submit{
    width: 124rpx;
    background: #EE751E;
    border-radius: 34rpx;
    color: #ffffff;
    font-size: 26rpx;
    line-height: 26rpx;
    padding: 20rpx 0;
    text-align: center;
    margin-left: 40rpx;
    align-self: flex-start;
  }
  .input-b{
    background-color: #eeeeee;
    border-radius: 18px;
    padding: 6px 10px;
    margin-bottom: 16px;
    flex: 1;
  }
}
.sex-box{
  line-height: 110rpx;
  text-align: center;
  margin: 0 30rpx;
}
.region-box{
  text-align: center;
  .title{
    line-height: 90rpx;
    background-color: #F2F2F2;
    display: flex;
    justify-content: space-between;
    color: #EE751E;
  }
  .picker-view{
    height: 500px;
    .item {
      line-height: 34px;
    }
  }
}
.background-list{
  padding: 30rpx 40rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .list-items{
    .item{
      display: flex;
      justify-content: space-between;
      margin: 0 auto 12rpx auto;
      width: 648rpx;
    }
    .grd-al{
      width: 318rpx;
      height: 280rpx;
      border-radius: 12rpx;
      overflow: hidden;
      position: relative;
    }
    .tips{
      position: absolute;
      top: 16rpx;
      right: 24rpx;
      height: 38rpx;
      width: 38rpx;
      .img{
        width: 100%;
        height: 100%;
      }
    }
  }
  .bottom-b{
    font-size: 32rpx;
    line-height: 32rpx;
    padding: 26rpx 0;
    background: #999999;
    border-radius: 42rpx;
    margin: 20rpx 40rpx 0 40rpx;
    text-align: center;
    color: #ffffff;
  }
  .header-list-items{
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .header-img{
      width: 108rpx;
      height: 108rpx;
      border-radius: 50%;
      margin: 0 27rpx 54rpx 27rpx;
    }
    .hes-hek{
      width: 162rpx;
      position: relative;
    }
    .tips {
      position: absolute;
      bottom: 54rpx;
      right: 27rpx;
      height: 38rpx;
      width: 38rpx;
      .img {
        width: 100%;
        height: 100%;
      }
    }
  }
}
.header-box{
  width: 180rpx;
  text-align: center;
  color: #999999;
  font-size: 24rpx;
  position: relative;
  margin: 0 auto 40rpx auto;
  .img{
    width: 180rpx;
    height: 180rpx;
    border-radius: 50%;
    margin-bottom: 18rpx;
  }
  .photo{
    position: absolute;
    right: 0;
    top: 120rpx;
    width: 58rpx;
    height: 58rpx;
  }
}
#canvasImg {
  visibility: hidden;
  position: absolute;
  left: -100%;
  width: 203px;
  height: 239px;
}
.lext-ftsj{
  width: 58vw;
  font-size: 14px;
}
:deep(.input-bg-user .is-input-border){
  border-radius: 18px;
  background-color: #e5e5e5;
}
:deep(.user-edit .uni-list-item__content-title) {
  color: #666666;
  min-width: 24px;
}
:deep(.user-edit .uni-list-item__extra-text) {
  font-size: 14px;
  color: #333333;
}
:deep(.user-edit .uni-list-item__container) {
  padding: 16px 0;
}
:deep(.user-edit .uni-list-item--hover) {
  background-color: #ffffff;
}
</style>
